<template>
    <div class="login">
        <div>
            <div>
                <img src="src/assets/images/logo.svg" alt="logo">
                <n-gradient-text gradient="linear-gradient(90deg, red 0%, green 50%, blue 100%)">社区心愿收集
                </n-gradient-text>
            </div>
            <n-form ref="formRef" :model="loginForm" :rules="rules">
                <n-form-item path="username" label="账号">
                    <n-input
                        v-model:value="loginForm.username"
                        placeholder="请输入" />
                </n-form-item>
                <n-form-item path="password" label="密码">
                    <n-input
                        v-model:value="loginForm.password"
                        type="password"
                        show-password-on="mousedown"
                        placeholder="请输入" />
                </n-form-item>
                <n-form-item path="code" label="验证码">
                    <n-input
                        placeholder="请输入"
                        style="width: 63%"
                        v-model:value="loginForm.code"
                        @keydown.enter.prevent />
                    <img @click="relodCaptcha(loginForm.uuid)" :src="loginForm.img" alt="codeUrl" class="login-code-img">
                </n-form-item>
                <n-row :gutter="[0, 24]">
                    <n-col :span="24">
                        <div style="display: flex; justify-content: flex-end">
                            <n-button round type="primary" @click="handleClick">登陆</n-button>
                        </div>
                    </n-col>
                </n-row>
            </n-form>
        </div>
    </div>
</template>
<script setup lang="ts">
import {reactive} from 'vue';
import {FormRules, FormInst, useMessage, useDialog, useNotification, FormItemRule} from 'naive-ui';
import {Login, CaptchaCreate, CaptchaImg} from '@/api/login';
import router from "@/router";
window.$message = useMessage();
window.$dialog = useDialog();
window.$notification = useNotification();
interface ModelType {
    username: string | null
    password: string | null
    code: string | null
    uuid: string | null
    img: string | null
}
// 初始化加载二维码
initImg();
async function initImg() {
    const { data } = await CaptchaCreate();
    loginForm.uuid = data;
    await relodCaptcha(data)
}

const relodCaptcha = async (uuid: string) => {
    CaptchaImg(uuid).then(({ code, data }: any) => {
        if (code === 200) {
            loginForm.img = `data:image/gif;base64,${data}`;
        } else {
            initImg();
        }
    }).catch((err) => {
        initImg();
    });

}

const formRef = ref<FormInst | null>(null)
// 定义属性
const loginForm = reactive<ModelType>({
    username: '',
    password: '',
    code: '',
    uuid: '',
    img: ''
});

const rules: FormRules = {
    username: [
        {
            required: true,
            validator(rule: FormItemRule, value: string) {
                if (!value) {
                    return new Error('用户名不能为空')
                }
                return true
            },
            trigger: ['input', 'blur']
        }
    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: ['input', 'blur']
        }
    ],
    code: [
        {
            required: true,
            message: '验证码不能为空',
            trigger: ['input', 'blur']
        }
    ]
}

/**
 * 提交表单
 */
async function handleClick() {
    const valid = await formRef.value?.validate();
    if (!valid) {
        const { code, data } : any = await Login(loginForm);
        if (code === 200) {
            // 存token
            localStorage.setItem('token', data.tokenHead + data.token);
            // 跳转社区人员界面
            router.push({path: '/'});
        } else {
            await initImg()
        }
    }
}
</script>
<style lang="scss" scoped>
.login {
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
    // 文字与图片对齐的关键 弹性布局
    display: flex;
    > div {
        height: 50%;
        width: 25%;
        left: 50%;
        margin: auto;
        font-size: 24px;
        > div {
            text-align: center;

            > img {
                vertical-align: middle;
            }

            > n-gradient-text {
                display: inline-block;
            }
        }
    }
}
.login-code-img {
    height: 38px;
}
</style>
